import Form from '../../models/forms';
import FormDatas from '../../models/formDatas';


export async function createForm(ctx) {
  const form = new Form(ctx.request.body.forms)

  await form.save().then((form) => {
    let response;

    response = {
      code: 10001,
      message: '添加成功',
      data: form
    }
    ctx.body = response
  }, (err) => {
    let response;
    console.log(err)
    if (err.code === 11000)
      response = {
        code: 11000,
        message: '该数据表名已存在',
        data: {}
      }
    else
      response = {
        code: 10002,
        message: err.message,
        data: {}
      }
    ctx.body = response
  })

}
export async function getForms (ctx) {
  const forms = await Form.find()
  ctx.body = { 
        code: 10001,
        message: '获取自定义表单列表成功',
        data: forms
   }
}
export async function getForm(ctx, next) {

  await Form.findById(ctx.params.id).then((form) => {
    let response;
    if (form) {
      response = {
        code: 10001,
        message: '成功',
        data: form
      }
    } else {
      response = {
        code: 10004,
        message: '没有数据',
        data: {}
      }
    }
    // ctx.body=JSON.stringify(response)
    ctx.body = response
  }, (err) => {
    ctx.body = {
      code: 10001,
      message: err
    }
  })
  if (next) {
    return next()
  }
}

export async function updateForm(ctx) {
  const form = ctx.body.forms

  Object.assign(form, ctx.request.body.forms)

  await forms.save().then((form) => {
    ctx.body = {
        code: 10001,
          message: '修改成功',
      form:form
    }
  })
}

// TODO
// 1.测试用例
// 1.1如果传入的字段超出自定义表单中定义字段
// 1.2如果传入的字段少于自定义表单中定义字段
export async function dynamicData(ctx,next) {
  const request_data = ctx.request.body.datas;
  const request_id = ctx.params.id
  await Form.findById(request_id).then(form => {
    let dataObj = form.form_datajson;
    let validator = true;
    let validateObj = {};
    let validateDatas = {}
    validateObj._creator = request_id;
    for (var props in dataObj) {
      // console.log(dataObj.props.verify,)
      let verify = checkValidator(dataObj[props].verify, request_data[props])
      if (!verify) {
        validator = false;
        ctx.body = {
          code: 10004,
          message: '有字段类型错误保存失败'
        }
      } else {
        validateDatas[props] = request_data[props]
      }
    }
    validateObj.datas = validateDatas;
    return validateObj;
  }).then(data => {
    const formdata = new FormDatas(data);
   return formdata.save().then(formdata => {
      ctx.body = {
        code: 10004,
        message: '保存数据成功',
        data: formdata
      }

    })
  }).catch(err => {
    ctx.throw(500, err)
  })

}

function checkValidator(rules, value) {
  let flag = true;
  switch (rules) {
    case 'string':

      flag = /^[\u4E00-\u9FA5A-Za-z0-9_]+$/.test(value)
      break
    default:
      flag = true
      break
  }
  console.log(rules, value, '检查类型', flag)
  return flag
}
